package com.gusti.admincasa.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gusti.admincasa.dao.IMessageDao;
import com.gusti.admincasa.model.Message;
import com.gusti.admincasa.model.User;
import com.gusti.admincasa.util.Debug;

/**
 * 
 * @author gusti
 *
 */
@Repository
public class MessageDao extends ProjectDao<Message> implements IMessageDao {

	public Message findMessage( long id ) {
		Message message = new Message();

		Query query = null;
		try {
			query = em.createQuery( "FROM Message as msg WHERE msg.id = :messageId" );
			query.setParameter( "messageId", id );
			message = (Message)query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
		}

		return message;
	}

	@SuppressWarnings("unchecked")
	public List<Message> listMessages( User user ) {
		List<Message> messages = new ArrayList<Message>();

		Query query = null;
		try {
			query = em.createQuery( "FROM Message as msg WHERE msg.owner = :user AND msg.readed = false" );
			query.setParameter( "user", user );
			messages = (List<Message>)query.getResultList();
		} catch ( Exception e ) {
			Debug.error( e );
		}

		return messages;
	}

}
